package com.xdcplus.web.component;


import com.xdcplus.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CommonHelperService {

    @Autowired
    private RedisUtils redisUtils;

    private static String keyPrefix = "CODING";

    public String getFlowCoding(String seperateCode,
                                Integer len,Integer timeMode) {

        /// 流水码日期模式
        String timeFormat = "";
        long expireTime = 5L; /// 单位分钟  按照时间窗定义过期值
        switch (timeMode) {

            case 0: /// 自定义
                timeFormat = seperateCode;
                expireTime = 5L;
                break;

            case 1: /// 分级
                timeFormat = LocalDateTime.now()
                        .format(DateTimeFormatter.ofPattern("HH:mm"));
                expireTime = 5L;
                break;

            case 2: /// 日级
                timeFormat = LocalDateTime.now()
                        .format(DateTimeFormatter.ofPattern("MM-dd"));
                expireTime = 60*25L;
                break;

        }

        String key = String.format("%s_%s_%s",keyPrefix,
                seperateCode, timeFormat);
        Long incrVal = redisUtils.incrBy(key, 1L);
        redisUtils.expire(key,expireTime, TimeUnit.MINUTES);
        return StringUtils.leftPad(String.valueOf(incrVal), len,"0");
    }

}
